package com.jxit0573.android.lib.net;

import com.jxit0573.android.lib.util.DeviceUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author jia
 */
public class RequestUtils {

    private static volatile RequestUtils instance;
    private static OkHttpClient client;

    static {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS);
        clientBuilder.addInterceptor(chain -> {
            Request request = chain.request()
                    .newBuilder()
                    .header("platform", "Android")
                    .header("brand", DeviceUtils.getBrand())
                    .header("model", DeviceUtils.getModel())
                    .header("release", DeviceUtils.getRelease())
                    .header("sdk", DeviceUtils.getSdk() + "")
                    .build();
            return chain.proceed(request);
        });
        client = clientBuilder.build();
    }

    private RequestUtils() {
    }

    public static RequestUtils getInstance() {
        if (instance == null) {
            synchronized (RequestUtils.class) {
                if (instance == null) {
                    instance = new RequestUtils();
                }
            }
        }
        return instance;
    }

    public static void initClient(OkHttpClient okHttpClient) {
        client = okHttpClient;
    }

    public static OkHttpClient getClient() {
        return client;
    }

    public static GetRequestBuilderBase get() {
        return new GetRequestBuilderBase();
    }

    public static PostFormRequestBuilderBase post() {
        return new PostFormRequestBuilderBase();
    }

    public static PostJsonRequestBuilderBase postJson() {
        return new PostJsonRequestBuilderBase();
    }

    public static UploadRequestBuilderBase upload() {
        return new UploadRequestBuilderBase();
    }

    public static void cancel(Object tag) {
        Dispatcher dispatcher = client.dispatcher();
        for (Call call : dispatcher.queuedCalls()) {
            if (Objects.requireNonNull(call.request().tag()).toString().contains(tag.toString())) {
                call.cancel();
            }
        }
        for (Call call : dispatcher.runningCalls()) {
            if (Objects.requireNonNull(call.request().tag()).toString().contains(tag.toString())) {
                call.cancel();
            }
        }
    }

    public static void cancelAll() {
        client.dispatcher().cancelAll();
    }

    public <T> void execute(RequestCall call, BaseRequestCallback<T> callback) {
        call.getCall().enqueue(callback);
    }
}
